package com.welsmann.app.start.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.welsmann.app.start.common.StartConst;
import com.welsmann.app.start.dao.BaseDAO;
import com.welsmann.app.start.dao.ISiteDAO;
import com.welsmann.app.start.entity.Site;

@Component("SiteDAO")
public class SiteDAO extends BaseDAO implements ISiteDAO {

	private HibernateTemplate _ht = null;

	@Override
	public int click(String id) {
		_ht = new HibernateTemplate(super.sessionFactory);
		Site site = _ht.get(Site.class, id);
		if (site != null) {
			site.setCount(site.getCount() + 1);
			_ht.save(site);
		}
		return site == null ? 0 : site.getCount();
	}

	@Override
	public List<Site> getAll() {
		_ht = new HibernateTemplate(super.sessionFactory);
		return _ht.find("from Site order by type,count");
	}

	@Override
	public List<Site> getTypeAll(String type) {
		_ht = new HibernateTemplate(super.sessionFactory);
		return _ht.find("from Site where type = ? order by count", type);
	}

	@Override
	public List<Site> getTopAll() {
		_ht = new HibernateTemplate(super.sessionFactory);
		return _ht.find("from Site order by count desc limit ?", StartConst.SITE_TOP_LIMIT);
	}

	@Override
	public List<Site> getTypeTop(String type) {
		_ht = new HibernateTemplate(super.sessionFactory);
		return _ht.find("from Site s where s.type = ? order by s.count desc limit ?", type, StartConst.SITE_TOP_LIMIT);
	}

	@Override
	public Site getById(String id) {
		_ht = new HibernateTemplate(super.sessionFactory);
		return _ht.get(Site.class, id);
	}

	@Override
	public Site getByAlias(String alias) {
		_ht = new HibernateTemplate(super.sessionFactory);
		List<Site> lstSite = _ht.find("from Site where alias = ?", alias);
		return lstSite != null && lstSite.size() > 0 ? lstSite.get(0) : null;
	}
}
